<template>
  <div class="bg-style">
    <i-pageBody class="add_i-color">
      <div slot="page-main">
        <div class="container container-space container-space--vertical">
          <div class="container-space__child">
            <Button type="primary" @click="handleCreate">新增</Button>
            <Button
              type="default"
              @click="handleAction"
              :loading="loading.execute"
              >执行</Button
            >
          </div>
          <div class="container-space__child">
            <Table
              :columns="columns"
              :data="nextData"
              disabled-hover
              border
              show-summary
              :summary-method="handleSummary"
              :loading="tableLoading"
            ></Table>
          </div>
          <div class="container-space__child " v-show="nextData.length">
            <div class="container-page">
              <PageHeader
                :total="formdata.total"
                :page-size="formdata.pageSize"
                :page="formdata.page"
              ></PageHeader>
              <Page
                :total="formdata.total"
                :page-size="formdata.pageSize"
                :current="formdata.page"
                @on-change="handlePage"
                show-sizer
                @on-page-size-change="handlePageSize"
              />
            </div>
          </div>
        </div>
      </div>
    </i-pageBody>
    <Modal v-model="edit.modal" width="800" title="新增">
      <div>
        <Form
          ref="editForm"
          :model="edit.formdata"
          :rules="edit.rules"
          :label-width="120"
        >
          <FormItem prop="custName" label="选择用户：">
            <i-input
              readonly
              placeholder="请选择用户"
              v-model="edit.formdata.custName"
            >
              <Button
                type="primary"
                @click="customer.modal = true"
                slot="append"
              >
                用户选择
              </Button>
            </i-input>
          </FormItem>
          <FormItem prop="equipId" label="选择设备：">
            <Select
              v-model="edit.formdata.equipId"
              placeholder="请选择设备"
              style="100%"
            >
              <Option
                :value="value"
                v-for="({ label, value }, index) in options.equips"
                :key="index"
                >{{ label }}</Option
              >
            </Select>
          </FormItem>
          <FormItem prop="load" label="可调负荷：">
            <div class="container-space">
              <InputNumber
                :min="0"
                style="width:120px"
                v-model="edit.formdata.load"
                class="container-space__child"
              ></InputNumber>
              <span class="container-space__child">kW</span>
            </div>
          </FormItem>
          <FormItem prop="status" label="状态设置：">
            <RadioGroup v-model="edit.formdata.status">
              <Radio label="1">开</Radio>
              <Radio label="0">关</Radio>
            </RadioGroup>
          </FormItem>
        </Form>
      </div>
      <div slot="footer">
        <Button type="default" @click="edit.modal = false">
          取消
        </Button>
        <Button type="primary" @click="handleSubmit" :loading="loading.save">
          保存
        </Button>
      </div>
    </Modal>
    <Modal v-model="update.modal" width="800" title="修改">
      <div>
        <Form ref="updateForm" :model="update.formdata" :label-width="120">
          <FormItem prop="load" label="可调负荷：">
            <div class="container-space">
              <InputNumber
                :min="0"
                style="width:120px"
                v-model="update.formdata.load"
                class="container-space__child"
              ></InputNumber>
              <span class="container-space__child">kW</span>
            </div>
          </FormItem>
        </Form>
      </div>
      <div slot="footer">
        <Button type="default" @click="update.modal = false">
          取消
        </Button>
        <Button
          type="primary"
          @click="handleUpdateSubmit"
          :loading="loading.update"
        >
          保存
        </Button>
      </div>
    </Modal>
    <Modal v-model="customer.modal" width="1200" title="用户选择">
      <div class="container container-space container-space--vertical">
        <div class="container-space__child">
          <Form ref="customerForm" :model="customer.formdata">
            <Row :gutter="20">
              <i-col :span="10">
                <FormItem prop="custNo" label="用户编号：" :label-width="85">
                  <Input
                    v-model="customer.formdata.custNo"
                    placeholder="请输入用户编号"
                    clearable
                  />
                </FormItem>
              </i-col>
              <i-col :span="10">
                <FormItem prop="custName" label="用户名称：" :label-width="85">
                  <Input
                    v-model="customer.formdata.custName"
                    placeholder="请输入用户名称"
                    clearable
                  />
                </FormItem>
              </i-col>
              <i-col :span="4">
                <Button
                  type="primary"
                  @click="handleCustomerSearch"
                  :loading="loading.customer.search"
                >
                  查询
                </Button>
              </i-col>
            </Row>
          </Form>
        </div>
        <div class="container-space__child">
          <Table
            ref="customerTable"
            :columns="customer.columns"
            :data="customer.data"
            border
            stripe
            :max-height="400"
          ></Table>
        </div>
        <div class="container-space__child">
          <div class="container-page">
            <PageHeader
              :total="customer.formdata.total"
              :page-size="customer.formdata.pageSize"
              :page="customer.formdata.page"
            ></PageHeader>
            <Page
              :total="customer.formdata.total"
              :page-size="customer.formdata.pageSize"
              :current="customer.formdata.page"
              @on-change="handleCustPage"
              show-sizer
              @on-page-size-change="handleCustPageSize"
            />
          </div>
        </div>
      </div>
      <div slot="footer">
        <Button type="default" @click="customer.modal = false">
          取消
        </Button>
      </div>
    </Modal>
  </div>
</template>

<script>
import PageHeader from "../../components/page-header";
import {
  TABLE_DECOMPOSE_COLUNMS,
  TABLE_CUSTOMER_COLUNMS,
  EDIT_RULES,
  DEV_CONTROL_OPTIONS
} from "./constants";
import {
  getCustomerList,
  getEquipList,
  addEmergency,
  updateEmergency,
  deleteEmergency,
  getEmergencySelect,
  executeEmergency
} from "@/api/scada";
export default {
  name: "emergency-decompose",
  props: {},
  data() {
    const columns = [
      ...TABLE_DECOMPOSE_COLUNMS,
      {
        title: "操作",
        width: 160,
        fixed: "right",
        align: "center",
        render: (h, params) => {
          const { row } = params;
          return h("span", [
            h(
              "Button",
              {
                props: {
                  type: "primary",
                  size: "small"
                },
                style: {
                  "margin-right": "8px"
                },
                nativeOn: {
                  click: () => {
                    this.handleUpdate(row);
                  }
                }
              },
              "修改"
            ),
            h(
              "Button",
              {
                props: {
                  type: "error",
                  size: "small"
                },
                nativeOn: {
                  click: () => {
                    this.handleDelete(row);
                  }
                }
              },
              "删除"
            )
          ]);
        }
      }
    ];
    const custColumns = [
      ...TABLE_CUSTOMER_COLUNMS,
      {
        title: "操作",
        width: 160,
        align: "center",
        render: (h, params) => {
          const { row } = params;
          return h("span", [
            h(
              "Button",
              {
                props: {
                  type: "primary",
                  size: "small"
                },
                style: {
                  "margin-right": "8px"
                },
                nativeOn: {
                  click: () => {
                    this.handleCustSelect(row);
                  }
                }
              },
              "选择"
            )
          ]);
        }
      }
    ];

    return {
      loading: {
        normal: false,
        save: false,
        update: false,
        delete: false,
        execute: false,
        customer: {
          search: false,
          normal: false
        }
      },
      formdata: {
        controlsId: "",
        instructId: "",
        areaNo: "",
        goback: "no",
        page: 1,
        pageSize: 10,
        total: 0
      },
      options: {
        customers: [],
        equips: []
      },
      columns,
      data: [],
      customer: {
        modal: false,
        columns: custColumns,
        data: [],
        formdata: {
          custName: "",
          custNo: "",
          areaNo: "",
          page: 1,
          pageSize: 10,
          total: 0
        }
      },
      edit: {
        modal: false,
        formdata: {
          custId: "",
          custName: "",
          equipId: "",
          load: 0,
          status: "1"
        },
        rules: EDIT_RULES
      },
      update: {
        modal: false,
        formdata: {
          load: 0,
          id: ""
        }
      },
      delete: {
        id: ""
      }
    };
  },
  computed: {
    tableLoading() {
      const {
        loading: { normal, page }
      } = this;
      return normal || page;
    },
    nextData() {
      const { data } = this;
      return data.map((element) => {
        const { sbkzzt } = element;
        const { label: sbkzztLabel } =
          DEV_CONTROL_OPTIONS.find((option) => option.value === sbkzzt) || {};
        return {
          ...element,
          sbkzztLabel
        };
      });
    }
  },
  created() {},
  mounted() {
    this.handleRouter();
  },
  watch: {
    "edit.formdata.custId"(val) {
      this.edit.formdata.equipId = "";
      this.options.equips = [];
      if (this.edit.formdata.custId) {
        this.getEquipList();
      }
    }
  },
  methods: {
    handleRouter() {
      const {
        query: { controlsId, instructId, areaNo, goback }
      } = this.$route;
      this.formdata.controlsId = controlsId;
      this.formdata.instructId = instructId;
      this.formdata.areaNo = areaNo;
      this.formdata.goback = goback;
      this.getEmergencyList();
      this.getCustomerList();
    },
    handleCustomerSearch() {
      this.customer.formdata.page = 1;
      this.getCustomerList("search");
    },
    handleCustomerReset() {},
    handleCustSelect(row) {
      const { custId, custName } = row;
      this.edit.formdata.custName = custName;
      this.edit.formdata.custId = custId;
      this.customer.modal = false;
    },
    handlePage(page) {
      this.formdata.page = page;
      this.getEmergencyList();
    },
    handlePageSize(pageSize) {
      this.formdata.pageSize = pageSize;
      this.getEmergencyList();
    },
    handleCustPage(page) {
      this.customer.formdata.page = page;
      this.getCustomerList();
    },
    handleCustPageSize(pageSize) {
      this.customer.formdata.pageSize = pageSize;
      this.getCustomerList();
    },
    handleSubmit() {
      this.$refs.editForm.validate((valid) => {
        if (!valid) return;
        this.addEmergency();
      });
    },
    handleUpdateSubmit() {
      this.$refs.updateForm.validate((valid) => {
        if (!valid) return;
        this.updateEmergency();
      });
    },
    handleCreate() {
      this.edit.modal = true;
      this.$refs.editForm.resetFields();
    },
    handleAction() {
      this.executeEmergency();
    },
    handleUpdate(row) {
      const { controlsId, kdfh, sbid, id } = row;
      this.update.formdata.load = isNaN(kdfh) ? 0 : Number(kdfh);
      this.update.formdata.id = id;
      this.update.modal = true;
    },
    handleDelete(row) {
      const { id } = row;
      this.delete.id = id;
      this.$Modal.confirm({
        title: "提示",
        content: "是否确定删除？",
        onOk: () => {
          this.deleteEmergency();
        }
      });
    },
    handleSummary({ columns, data }) {
      const sums = {};
      columns.forEach((column, index) => {
        const key = column.key;
        if (index === 0) {
          sums[key] = {
            key,
            value: "总计"
          };
          return;
        } else if (key === "age") {
          const value = data
            .map((item) => Number(item[key]))
            .filter((element) => !isNaN(element))
            .reduce((prev, next) => prev + next, 0);
          sums[key] = {
            key,
            value
          };
        } else {
          sums[key] = {
            key,
            value: ""
          };
        }
      });
      return sums;
    },
    // 用户
    getCustomerList(loadingType = "normal") {
      this.loading.customer[loadingType] = true;
      let {
        customer: {
          formdata: { custName, custNo, page: currentPage, pageSize }
        },
        formdata: { areaNo }
      } = this;
      const params = {
        custName,
        custNo,
        areaNo,
        currentPage,
        pageSize
      };
      getCustomerList(params)
        .then((ret) => {
          const { code, result } = ret || {};
          if (code === 200) {
            const { totalNum, custom } = result || {};
            this.customer.data = custom || [];
            this.customer.formdata.total = totalNum || 0;
          }
        })
        .finally(() => {
          this.loading.customer[loadingType] = false;
        });
    },
    // 设备
    getEquipList() {
      const custId = this.edit.formdata.custId;
      getEquipList({ custId }).then((ret) => {
        const { code, result } = ret || {};
        if (code === 200) {
          this.options.equips = (result || []).map((element) => {
            const { equipmentid, equipmentname } = element;
            return {
              value: equipmentid,
              label: equipmentname
            };
          });
        }
      });
    },
    getEmergencyList(loadingType = "normal") {
      this.loading[loadingType] = true;
      let {
        formdata: { controlsId, page: currentPage, pageSize }
      } = this;
      const params = {
        controlsId,
        currentPage,
        pageSize
      };
      getEmergencySelect(params)
        .then((ret) => {
          const { code, result } = ret || {};
          if (code === 200) {
            const { totalNum, custom } = result || {};
            const { data } = custom || {};
            this.formdata.total = totalNum || 0;
            this.data = data || [];
          }
        })
        .finally(() => {
          this.loading[loadingType] = false;
        });
    },
    addEmergency() {
      this.loading.save = true;
      const {
        edit: {
          formdata: { custId, equipId, load, status }
        },
        formdata: { controlsId, instructId }
      } = this;
      const { label: equipName } =
        this.options.equips.find((option) => option.value === equipId) || {};
      const params = {
        custId,
        equipId,
        equipName,
        load,
        status,
        controlsId,
        instructId
      };
      addEmergency(params)
        .then((ret) => {
          const { code } = ret;
          if (code === 200) {
            this.$refs.editForm.resetFields();
            this.edit.modal = false;
            this.getEmergencyList();
          }
        })
        .finally(() => {
          this.loading.save = false;
        });
    },
    updateEmergency() {
      this.loading.update = true;
      const {
        update: {
          formdata: { id, load }
        }
      } = this;
      const params = {
        id,
        load
      };
      updateEmergency(params)
        .then((ret) => {
          const { code } = ret;
          if (code === 200) {
            this.update.modal = false;
            this.getEmergencyList();
          }
        })
        .finally(() => {
          this.loading.update = false;
        });
    },
    deleteEmergency() {
      this.loading.delete = true;
      const {
        delete: { id }
      } = this;
      deleteEmergency({ id })
        .then((ret) => {
          const { code } = ret;
          if (code === 200) {
            this.getEmergencyList();
          }
        })
        .finally(() => {
          this.loading.delete = false;
        });
    },
    executeEmergency() {
      this.loading.execute = true;
      const {
        formdata: { controlsId, instructId }
      } = this;
      const params = {
        controlsId,
        instructId
      };
      executeEmergency(params)
        .then((ret) => {
          const { code } = ret;
          if (code === 200) {
            this.$Message.success("执行成功");
            this.getEmergencyList();
            console.log(this.formdata);
            if (this.formdata.goback === "yes") {
              setTimeout(() => {
                this.$router.go(-1);
              }, 500);
            }
          }
        })
        .finally(() => {
          this.loading.execute = false;
        });
    }
  },
  components: { PageHeader }
};
</script>
<style scoped lang="scss">
.bg-style {
  width: 100%;
  height: 100%;
}
.container {
  padding: 20px;
  height: 100%;
  overflow: auto;
}
.container-title {
  padding-left: 10px;
  font-size: 16px;
  color: #333;
  position: relative;
}
.container-title::before {
  content: "";
  position: absolute;
  left: 0;
  top: 50%;
  transform: translateY(-50%);
  display: inline-block;
  width: 4px;
  height: 16px;
  background-color: #0893fd;
  line-height: 16px;
}

.container-space > .container-space__child:not(:last-child) {
  margin-right: 20px;
}
.container-space.container-space--vertical
  > .container-space__child:not(:last-child) {
  margin-bottom: 20px;
  margin-right: 0;
}
.container-space--inner {
  padding: 20px;
}

.container-align--center {
  text-align: center;
}
.container-align--right {
  text-align: right;
}
.container-page {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
</style>
<style lang="scss" scoped>
/deep/ .ivu-table-tip table tr td {
  text-align: center;
  background-image: url("~@/assets/img/zwsj.png");
  background-position: center 60px;
  background-repeat: no-repeat;
  color: #999;
  height: 369px;
  background-size: 190px;
  span {
    display: none;
  }
}
</style>
